<?php

	// +----------------------------------------------------------------------
	// | 站内消息
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\controller\ucenter\admin;

	use app\controller\admin\Common;
	use app\model\ucenter\EmailTemplate as EmailTemplateModel;
	use yicmf\builder\Edit;
	use yicmf\builder\Table;
	use app\event\ucenter\Notice as NoticeEvent;
	use app\event\ucenter\User as UserEvent;
	use app\model\ucenter\Message as MessageModel;
	use app\model\ucenter\UserGrade as UserGradeModel;
	use app\model\ucenter\User as UserModel;

	class  Message extends Common
	{
		protected function initialize()
		{
			parent::initialize();
		}


		public function _filter()
		{
			$map = [];
			$map[] = ['status', '>', -2];
			if (!UserEvent::isAdministrator($this->user)) {
				$map[] = ['user_id', '=', $this->user['id']];
			}
			return $map;
		}

		public function index()
		{
			// 读取规则列表
			// 显示页面
			$statusOptions = [
				[
					'id' => 1,
					'value' => '已读',
				],
				[
					'id' => 2,
					'value' => '未读',
				]
			];
			// 显示页面
			$builder = new Table();
			$builder->model(MessageModel::class)
				->where($this->_filter())
				->order('id DESC')
//                ->setSearchPostUrl('ucenter/admin/Message/index', '')
//				->buttonUpdate('ucenter/admin/Message/add')
				->searchTextLike('content', '通知内容：')
				->searchSelect('status', '状态：', $statusOptions)
				->keyId()
				->keyTitle('标题', false, '200')
				->keyText('content', '详细', false, '404')
				->keySwitch('is_read', '读取', '已读|未读', false, 92)
				->keyUser('user_id', '收件人')
				->keyUser('from_user_id', '发件人')
				->keyIp()
				->keyCreateTime()
				// ->actionView('read?id={$id}','查看')
				->actionDelete();
			return $builder->fetch();
		}

		public function admin()
		{
			// 读取规则列表
			$statusOptions = [
				[
					'id' => 1,
					'value' => '已读',
				],
				[
					'id' => 0,
					'value' => '未读',
					'select' => 1,
				]
			];
			$map = [];
			if (!$this->request->has('field')) {
				$map[] = ['is_read', '=', 0];
			}
			$map[] = ['status', '>', -2];
			$map[] = ['user_id', '=', $this->user['id']];
			// 显示页面
			$builder = new Table();
			$builder->model(MessageModel::class)
				->where($map)
				->order('id DESC')
				->searchTextLike('content', '通知内容：')
				->searchSelect('is_read', '状态：', $statusOptions)
				->keyId()
				->keyTitle('标题', false, '200')
				->keyText('content', '详细', false, '404')
				->keySwitch('is_read', '读取', '已读|未读', false, 92)
				->keyUser('user_id', '收件人')
				->keyUser('from_user_id', '发件人')
				->keyIp()
				->keyCreateTime()
				->actionForbid('read?id={$id}', '已读')
				->actionDelete();
			return $builder->fetch();
		}

		/**
		 * 新增消息
		 */
		public function add()
		{
			if ($this->request->isPost()) {
				halt($this->request->post());
				$result = NoticeEvent::sendByAdmin($this->request->post(), $this->user);
				if (0 == $result['code']) {
					$this->_returnSuccess( $result['message'], false, false);
				} else {
					$this->_returnError( '发送消息失败，失败信息【' . $result['message'] . '】');
				}
			} else {
				$data = [];//
				$template = EmailTemplateModel::where('status', 1)->where('id', 6)->column('title', 'id');
				$builder = new Edit();
				$users = UserModel::where('status', 1)->count();
				if ($users > 10000) {
					$tips = '单次发送用户数最多10000个，当前有效用户' . $users . '个，需要分批发送，默认从第一批';
				}
				$builder->title('发送通知')
					->keyTextInline('title', '标题')
					->keyTextArea('content', '内容')
//					->keyCheckBox('type', '接收方式', ['站内信', 'APP推送','邮件', '微信公众号', '短信'])
					->keyCheckBox('types', '接收方式', ['message' => '站内信', 'app' => 'APP推送', 'email' => '邮件'], '', ['message'])
					->keyRadio('to_type', '发送方式', ['指定用户ID', '指定手机号', '指定邮箱', '卖家组', 'VIP卖家', '全部'])
					->keyRadio('email_template_id', '邮件模板', $template, '', 6)
					->keyRadio('user_grade_id', '用户组', UserGradeModel::where('status', 1)->column('title', 'id'), '', 1)
					->keyNumber('user_id', '用户ID')
					->keyMobile('mobile', '手机号')
					->keyEmail('email', '邮件地址');
				if ($users > 10000) {
					$builder->keyNumber('user_page', '用户分页', $tips, 1);
				}
				$builder->setTrigger('to_type', 0, 'user_id')
					->setTrigger('to_type', 1, 'mobile')
					->setTrigger('to_type', 2, 'email,template_id')
					->setTrigger('to_type', 3, 'user_grade_id,user_page')
					->setTrigger('to_type', 4, 'user_page')
					->setTrigger('to_type', 5, 'user_page')
					->setTrigger('types', 'email', 'email_template_id')
					->data($data)
					->buttonSubmit();
				return $builder->fetch();
			}
		}

		/**
		 * 设置已读
		 * @throws \think\Exception
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/5/8 16:49
		 */
		public function read()
		{
			$message = $this->user->messages()->where('id', $this->request->param('id'))->find();
			if ($message) {
				$message['is_read'] = 1;
				$message->save();
				$this->_returnSuccess( '操作成功');
			} else {
//                $this->_returnError( '留言不存在');
			}
		}

		/**
		 * 删除消息
		 */
		public function delete()
		{
			$message = MessageModel::where('id', $this->request->param('id'))->find();
			if ($message) {
				$message['status'] = -2;
				$message->save();
				$this->_returnSuccess( '删除成功');
			} else {
				$this->_returnSuccess( '操作失败');
			}
		}


	}
